<?php
namespace app\spider\service\content;
use app\common\service\EsSearchService;
use QL\QueryList;
use QL\Ext\CurlMulti;
use QL\Ext\AbsoluteUrl;
use think\Db;


abstract class  AbstractBaseService
{
    protected $params = [];

    public function __construct($params)
    {
        $this->params = $params;
    }

    /**
     * 内容采集
     * @param QueryList $ql
     * @param CurlMulti $curl
     * @param $r
     * @param $params
     * @return mixed
     */
    public abstract function process(QueryList $ql, CurlMulti $curl, $r);

    /**
     * 检测资源链接类型
     * @param $link
     * @param $site_url
     * @param string $cur_url
     * @return bool|array
     */
    protected function checkSourceLink($link, $site_url, $cur_url = ''){
        if(!$link){
            return false;
        }
        if(strstr($link,'magnet:') || strstr($link,'thunder://') || strstr($link,'ed2k://') || strstr($link,'ftp:')){
            $url = [
                'type' => 1,
                'link' => $link,
            ];
        }elseif(strstr($link,'javascript:')){
            return false;
        }else{
            $url = [
                'type' => 2,
                'link' => absolute_url($link, $site_url, $cur_url),
            ];
        }
        return $url;
    }


    /**
     * @param $sources
     * @param $url
     * @param $content
     * @param $site_id
     * @param $title
     */
    protected function saveData($sources, $url, $content, $site_id, $title) {
        $search_index_content = strip_tags($content);
        $search_index_content = preg_replace("/\s{2,}/"," ",$search_index_content);
        $search_index_content = preg_replace("/[\r\n]+/"," ",$search_index_content);
        $summary = mb_substr($search_index_content, 0, 300);
        if(count($sources) > 0){
            $film_data = array(
                'site_id' => $site_id,
                'title'   => $title,
                'content' => $content,
                'status'  => 1,
                'summary' => $summary,
                'gather_url' => $url,
                'c_time' => date('Y-m-d H:i:s',time()),
            );

            $film_id = Db::table('db_film')->insert($film_data,true, true);
            if($film_id){
                foreach($sources as $key => $value){
                    $sources_data['film_id'] = $film_id;
                    $sources_data['link'] = $value['link'];
                    $sources_data['type'] = $value['type'];
                    $sources_data['title'] = $value['title'];
                    Db::table('db_film_source')->insert($sources_data);
                }

                $film_data['id'] = $film_id;
                $es = EsSearchService::getInstance();
                $es->buildIndex($film_data);
            }
        }
    }
}
